/**
 * Created by CZ on 2017/4/6.
 */

module.exports = function($scope, $rootScope, RequestService, $localStorage, modelService, $state, commonConfig, $modal, echarts,$http){
    $rootScope.isShowFooter = false;
    console.log('用户信息--->',$rootScope.User);
    //////////////////////////////////////////////////获取用户头像///////////////////////////////////////////////////////////////////////
    getAvatar();
    $scope.Avatar = 'src/imgs/user/avatar.png';
    function getAvatar(){
        RequestService.Request(commonConfig.userApi+'user/user/getUserPhotoUUID?userId=' + $rootScope.User.detail.id, 'GET').then(function(response){
            console.log('--->',response);
            if(response !== 'NULL'){
                $scope.Avatar = $rootScope.imgApi+response
            }
        }, function(error){
            console.log(error);
        });
    }
    //用户主页控制
    $scope.MyHomepage = function(){
        switch($rootScope.User.authority){
            case 'CloudAdmin':
                $state.go('DeveloperManager.ManagerBaseInfo');
                break; //开发者首页
            case 'SchoolAdministrator':
                window.location.href = commonConfig.userHomepage;
                break; //学校管理员首页
        }
    };
    //获取用户（教师、学生拓展的用户信息）
    // console.log($rootScope.User);
    // getUserExtendInfo();
    // function getUserExtendInfo(){
    //     RequestService.Request(commonConfig.userApi+'user/user/getUserExtendById?userId=' + $rootScope.User.detail.id, 'GET').then(function(response){
    //         console.log(response);
    //         $rootScope.UserExtendInfo = response;
    //         $rootScope.User.UserExtendInfo = response;
    //         $localStorage.set('cloud',$rootScope.User);
    //     }, function(error){
    //         console.log(error);
    //     });
    // }
    //////////////////////////////////////////////////右侧菜单管理
    getAppTypeList();//获取用户可用的应用（按分类）
    function getAppTypeList(){
        RequestService.Request(commonConfig.userApi+'user/roleapp/getAppListGroupByUserId?userId='+$rootScope.User.detail.id, 'GET').then(function(response){
            // console.log(response.length);
            $scope.AppTypeList = response;
        }, function(error){
            console.log(error);
        });

    }
    //打开普通应用
    $scope.setCommonFun = function(){
        $rootScope.User.isCommonFun = false;
        $localStorage.set('cloud', $rootScope.User);
    };
    //////////////////////////////////////////////////课程表///////////////////////////////////////////////////////////////////////

    //课程表当天选中的样式
    function ScheduleActive(){
        setTimeout(function(){
            var day = new Date().getDay();
            if(day != 0 ){
                angular.forEach(angular.element('table tr'),function(val,i){
                    if(val.className !== 'divider'){
                        // console.log(val);
                        angular.element(val).find('th').eq(new Date().getDay()).addClass('active');
                        angular.element(val).find('td').eq(new Date().getDay()).addClass('active');
                    }
                })
            }
        },100);
    }
    //获取我的课表
    function getMySchedule(){
        RequestService.eduRequest('api/Course/OrgSchedule/GetSchedule?userCode=' + $rootScope.User.detail.userCode+'&yearId=0&isHasWeekEnd=false', 'GET').then(function(response){
            console.log(response);
            $scope.MySchedule = response.Data;
        }, function(error){
            console.log(error);
        });
    }
    getMySchedule();
    //获取班级课表
    function getClassSchedule(){
        RequestService.eduRequest('api/Course/OrgSchedule/GetClassSchedule?userCode=' + $rootScope.User.detail.userCode+'&yearId=0&isHasWeekEnd=false', 'GET').then(function(response){
            console.log(response);
            $scope.ClassSchedule = response.Data;
        }, function(error){
            console.log(error);
        });
    }
    getClassSchedule();
    //////////////////////////////////////////////////新闻公告///////////////////////////////////////////////////////////////////////
    getInfoCenterData();
    function getInfoCenterData(){
        //初始化tab分页值
        // $scope.InfoCenterIndex = 0;
        //获取当前新闻
        RequestService.Request(commonConfig.infoApi+'info/news?pageSize=8&tenantId='+$rootScope.User.detail.tenantId, 'GET').then(function(response){
            // console.log(response);
            $scope.News = response;
        }, function(error){
        console.log(error);
    });
        //获取当前公告
        RequestService.Request(commonConfig.infoApi+'info/notice?pageSize=8&pageNum=1&userId=' + $rootScope.User.detail.id+'&tenantId='+$rootScope.User.detail.tenantId+'&userId='+$rootScope.User.detail.id, 'GET').then(function(response){
            // console.log(response);
            $scope.Notice = response;
        }, function(error){
            console.log(error);
        });
    }
    getTodoData();
    function getTodoData(){
        //获取任务列表数据(已办)
        RequestService.Request(commonConfig.todoApi+'todo/todo?tenantId='+$rootScope.User.detail.tenantId+'&acceptUserId='+$rootScope.User.detail.id+'&isNewHours=72&pageSize=8', 'GET').then(function(response){
            console.log('--->',response);
            $scope.TodoList = response;
        }, function(error){
            console.log(error);
        });
    }
    //点击获取更多数据
    $scope.getMoreInfoList = function(page){
        // console.log(page);
        // $state.go('CloudUser.MoreInfoList', {'page' : page});
        $scope.setCommonFun(); //设置打开普通应用
        switch(page){
            case 'news':
                window.location.href = commonConfig.infoHomepage+'/newsListIndex/newsList';
                break;
            case 'notice':
                window.location.href = commonConfig.infoHomepage+'/noticeListIndex/noticeList';
                break;
            case 'unTodo':
                window.location.href = commonConfig.todoHomepage+'/manage';
                break;
            case 'hasTodo':
                window.location.href = commonConfig.todoHomepage+'/manage';
                break;
        }
    };
    //点击获取详情
    $scope.getDetail = function(page, id){
        // console.log(page, id);
        // $state.go('CloudUser.MoreInfoDetail', {'page' : page, 'id' : id});
        var url = null;
        switch(page){
            case 'news':
                url = commonConfig.infoHomepage+'/DetailNews/'+id;
                break;
            case 'notice':
                url = commonConfig.infoHomepage+'/DetailNotice/'+id;
                break;
            default:
                url = page+'&username='+$rootScope.User.username;
                console.log(url);
                setTodoStatus(id);
                break;
        }
        //保存确认为常用应用窗口
        setCommonFunCondition();
        layer.open({
            type : 2,
            title : false,
            fix : false,
            maxmin : true,
            shadeClose : true,
            area : ['1000px', '500px'],
            content : url,   //模块由路由传递是否为常用应用控制界面的显示
            end : function(){
                setCommonFunCondition();
                getTodoData();
            }
        });
    };
    function setTodoStatus(id){
        RequestService.Request(commonConfig.todoApi+'todo/todo/setTodoStatus?id='+id, 'GET').then(function(response){
            console.log(response,'修改了待办状态');
        }, function(error){
            console.log(error);
        });
    }
    /////////////////////////////////////////////////点击添加常用App
    //弹出新窗口
    $scope.layerOpen = function(commonFun){
        // console.log(commonFun);
        //增加点击次数 (TODO 不需要点击次数)
        //addUserAppCommonlyFunClickCount(commonFun.id);
        //保存确认为常用应用窗口
        setCommonFunCondition()
        layer.open({
            type : 2,
            title : commonFun.appCommonlyFunctionName,
            fix : false,
            maxmin : true,
            shadeClose : true,
            area : ['1000px', '500px'],
            content : commonFun.appCommonlyFunctionUrl,   //模块由路由传递是否为常用应用控制界面的显示
            end : function(){
                //(TODO 不需要点击次数)
                //getUserCommonAppList(); //关闭后重新获取列表，排序更改
                setCommonFunCondition()
            }
        });
    };
    function setCommonFunCondition(){  //修改LS中常用应用状态
        $rootScope.User.isCommonFun = !$rootScope.User.isCommonFun;
        $localStorage.set('cloud', $rootScope.User);
    }
    //增加常用应用的点击次数
    function addUserAppCommonlyFunClickCount(id){
        RequestService.Request(commonConfig.userApi+'sys/userappcommonlyfunction/updateClickCount?id='+id, 'PUT').then(function(response){
            console.log(response,'增加了点击次数');
        }, function(error){
            console.log(error);
        });
    }
    //获取全部App列表
    getAllCommonAppList();
    function getAllCommonAppList(){
        RequestService.Request(commonConfig.userApi+'user/roleapp/getAppListWithCommonlyFunctionByUserId?userId=' + $rootScope.User.detail.id, 'GET').then(function(response){
            // console.log(response);
            $scope.AllCommonAppList = response;
        }, function(error){
            console.log(error);
        });
    }
    $scope.OpenCommonAppModel = function(){
        $modal.open({
            animation : true,
            templateUrl : './views/model/CommonFunctionsModel.html',
            keyboard:false,     //是否允许用ESC键关闭模态窗口
            backdrop:"static",  //显示灰色背景，在模态窗口关闭之前背景元素不可用
            // size : 'md',
            scope : $scope,
            windowClass : 'modelClass',
            controller : function($scope, $modalInstance){
                $scope.ok = function(){
                    $modalInstance.close();
                };
                $scope.cancel = function(){
                    $modalInstance.dismiss();
                }
            }
        });
    };
    //点击添加
    $scope.AddCommonApp = function(CommonAppId, checked){
        // console.log(checked);
        if(checked){     //去除常用应用
            RequestService.Request(commonConfig.userApi+'sys/userappcommonlyfunction/deleteByuserIdAndFuncId?userId=' + $rootScope.User.detail.id + '&funcId=' + CommonAppId, 'DELETE').then(function(res){
                // console.log(res);
                //刷新数据
                getAllCommonAppList();
                getUserCommonAppList();
            }, function(error){
                console.log(error);
            });
        } else { //添加常用应用
            var CommonApp = {
                "appCommonlyFunctionId" : CommonAppId,
                "id" : 0,
                "userId" : $rootScope.User.detail.id
            };
            RequestService.Request(commonConfig.userApi+'sys/userappcommonlyfunction?tenantId='+$rootScope.User.detail.tenantId, 'POST', CommonApp).then(function(res){
                // console.log(res);
                if(res.code == 0){
                    //刷新数据
                    getAllCommonAppList();
                    getUserCommonAppList();
                    // modelService.openTipsModel('提交成功'); //成功并跳转
                } else {
                    modelService.openTipsModel('新增失败');
                }
            }, function(error){
                console.log(error);
            });
        }

    };
    //获取用户常用App列表
    $scope.isChangeCommonApp = false;  // 通过页面ng-show 监听初始化swiper,保证初始化时显示slider为第一个
    getUserCommonAppList();
    function getUserCommonAppList(){
        RequestService.Request(commonConfig.userApi+'sys/userappcommonlyfunction/getUserAppCommonlyFunctionWithAppCommonlyFunctionList?userId=' + $rootScope.User.detail.id, 'GET').then(function(response){
            // console.log(response);
            $scope.isChangeCommonApp = true;
            $rootScope.UserCommonAppList = response;
            ///////////swiper
            var swiper = new Swiper('.swiper-container', {
                pagination : '.swiper-pagination',
                initialSlide : 0, //设定初始化时slide的索引。
                slidesPerView : 'auto', //设置slider容器能够同时显示的slides数量(carousel模式)。
                slidesPerGroup : 1, //在carousel mode下定义slides的数量多少为一组。
                paginationClickable : true,
                spaceBetween : 20,
                observer : true,//修改swiper自己或子元素时，自动初始化swiper
                observeParents : true//修改swiper的父元素时，自动初始化swiper
                // nextButton: '.swiper-button-next',
                // prevButton: '.swiper-button-prev',
            });
        }, function(error){
            console.log(error);
        });
    }
    function chartsInit(){
        var line = echarts.init(document.getElementById('line'));
        var lineOption = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                }
            },
            legend: {
                data: ['高一1班', '高一3班']
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: ['语文', '数学', '英语', '物理', '化学', '生物', '政治']
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    min: 0,
                    max: 100
                }
            ],
            series: [
                {
                    name: '高一1班',
                    type: 'line',
                    stack: '总量1',
                    itemStyle: {
                        normal: {
                            color: '#38ade3',
                            // lineStyle: {
                            //     color: '#f3d6d4'
                            // }
                        }
                    },
                    label: {
                        normal: {
                            show: true,
                            position: 'top'
                            // color:'#f3d6d4'
                        }
                    },
                    areaStyle: {normal: {
                        color:'#e6f6ff'
                    }},
                    data: [82, 93, 90, 93, 75, 93, 83]
                },
                {
                    name: '高一3班',
                    type: 'line',
                    stack: '总量2',
                    itemStyle: {
                        normal: {
                            color: '#e34c38',
                            // lineStyle: {
                            //     color: '#e34c38'
                            // }
                        }
                    },
                    label: {
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },
                    areaStyle: {normal: {
                        color:'#fff1f1'
                    }},
                    data: [80, 98, 75, 83, 98, 85, 92]
                }
            ]
        };
        line.setOption(lineOption);
        var bar = echarts.init(document.getElementById('bar'));
        var barOption = {
            color : ['#51a5cc'],
            tooltip : {
                trigger : 'axis',
                axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                    type : 'line'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            grid : {
                left : '3%',
                right : '4%',
                top : '30px',
                containLabel : true
            },
            xAxis : [
                {
                    type : 'category',
                    data : ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                    axisTick : {
                        alignWithLabel : true
                    }
                }
            ],
            yAxis : [
                {
                    type : 'value',
                    axisLabel : {
                        formatter : '{value} 元'
                    }
                }
            ],
            series : [
                {
                    name : '消费',
                    type : 'bar',
                    barWidth : '30%',
                    data : [10, 52, 200, 334, 390, 330, 220, 19, 32, 100, 374, 320]
                }
            ]
        };
        bar.setOption(barOption);
    }   //初始化图表函数
    ///////////////////////////////////////////////////获取板块数据//////////////////////////////////////////////////////////////
    // 获取板块框架信息
    var PiecesArr = []; //板块框架数组
    function getIndexPieces(){
        RequestService.Request(commonConfig.cloudApi+'cloud/usercloudindexmodule/getList?userId='+ $rootScope.User.detail.id+'&tenantId='+$rootScope.User.detail.tenantId, 'GET').then(function(res){
            console.log(res);
            $scope.piecesList = res;
            PiecesArr = [];
            angular.forEach($scope.piecesList,function(val,i){
                PiecesArr.push({ "childIds": val.childIds, "id": val.id});
            });
            /////////////////折线图 TODO 隐藏一卡通等图表数据
            // setTimeout(function(){   //避免异步执行找不到dom
            //     chartsInit()
            // },10)
            ////////////////////////课程表背景色
            ScheduleActive();
        }, function(error){
            console.log(error);
        });
    }
    getIndexPieces();
    function uploadPiecesArr(arr){
        console.log(arr);
        RequestService.Request(commonConfig.cloudApi+'cloud/usercloudindexmodule/insertUserDataList2?userId='+ $rootScope.User.detail.id+'&tenantId='+$rootScope.User.detail.tenantId,'POST',arr).then(function(res){
            // console.log(res);
            if(res.code===0){
                getIndexPieces();  //重新获取框架
            }
        },function(error){
            console.log(error);
        });
    }
    $scope.sortableOptions = {
        placeholder: "piece-occupied",   //拖拽时占位显示的样式
        connectWith: ".pieces-wrap",  //排序变化时连接容器的样式，随之变化（一般是两个排序容器时才有用）
        update: function(e, ui) {
            if (ui.item.sortable.model == "can't be moved") {
                ui.item.sortable.cancel();
            }
        },
        stop:function(){
            // console.log($scope.piecesList);
            //存储改变的数组id
            var arr = [];
            angular.forEach($scope.piecesList,function(val,i){
                arr.push({ "childIds": val.childIds, "id": val.id});
            });
            // //本地存储用户的对象
            // $localStorage.set('cloud-page-setup',arr);
            uploadPiecesArr(arr); //上传用户设置的信息
        },
        'ui-floating': "auto"  //设置移动方向
        // axis: 'x'
    };
    //板块修改功能，获取板块名字与id列表
    RequestService.Request(commonConfig.cloudApi+'cloud/html/getCloudIndexModuleKeyNameList','GET').then(function(res){
        // console.log(res);
        $scope.pieceNameList = res;
    },function(error){
        console.log(error);
    });
    $scope.resetPiece = function(Index,key){
        console.log(Index, key);
        //根据点击板块将数组中的key替换掉
        var oldIndex = null;
        angular.forEach(PiecesArr,function(val,i){
            if(val.id == key){
                oldIndex = i;
            }
        });
        if(oldIndex !== null){
            var temKey = PiecesArr[Index];   //存储被替换的数值
            PiecesArr[Index]= PiecesArr[oldIndex]; //将新值传给被替换位置
            PiecesArr[oldIndex]= temKey;     //存储被替换数值到替换数值原本的位置
        }else {
            PiecesArr[Index] =  {"childIds": [], "id": key}
        }
        console.log(PiecesArr);
        uploadPiecesArr(PiecesArr); //上传用户设置的信息

    };
    //新增页面标签
    $scope.addPieceTab = function(parentKey){
        var modalInstance = $modal.open({
            templateUrl: './views/model/PieceTabsModel.html',
            controller: require('./AddPieceTabsCtrl'),
            size: "md",
            windowClass:'modelClass',
            resolve: {  //将数据作为对象传入控制器中
                parentKey: function () {
                    return parentKey;
                },
                piecesList:function(){
                    return $scope.piecesList
                }
            }
        });
        modalInstance.result.then(function (res) { //	一个promise，窗口关闭时为resolved，窗口取消时为rejected
            //$modalInstance.close();调用的方法
            uploadPiecesArr(res); //上传用户设置的信息
        }, function () {
            //$modalInstance.dismiss();调用的方法

        });
    };
    //删除页面标签
    $scope.delPieceTab = function(parentKey){
        $scope.piecesList[parentKey].tabClose = !$scope.piecesList[parentKey].tabClose;
    };
    $scope.delTab = function(parentKey,id){
        // console.log(parentKey, id);
        angular.forEach(PiecesArr[parentKey].childIds,function(val,i){
            if(val === id){
                PiecesArr[parentKey].childIds.splice(i,1);
            }
        });
        //子菜单删除原理：每个TAB在数据库有固定的id,这个id作为tab唯一的识别值写死在dom中，
        //              传进来的id与数据库相同则删除数组，并将数组上传从而获取最新的板块数据
        uploadPiecesArr(PiecesArr); //上传用户设置的信息
    };
    //板块新增与删除
    $scope.pieceAddBtn = false;
    $scope.pieceTitle = '';
    $scope.addPiece = function(num){
        switch(num){
            case 0:$scope.pieceAddBtn = true;break;
            case -1:$scope.pieceAddBtn = false;break;
            case 1:addPiece();//标题输入框
            break;
        }
        function addPiece(){
            RequestService.Request(commonConfig.cloudApi+'cloud/html/insertFrame?tenantId='+$rootScope.User.detail.tenantId+'&title='+$scope.pieceTitle+'&userId='+$rootScope.User.detail.id,'POST').then(function(res){
                console.log(res);
               if(res.code===0){
                   PiecesArr.push({ "childIds":[], "id": res.message});
                   uploadPiecesArr(PiecesArr); //上传用户设置的信息
                   // //本地存储用户的对象
                   // $localStorage.set('cloud-page-setup',arr);
                   //重置数据
                   $scope.pieceAddBtn = false;
                   $scope.pieceTitle = '';
               }
            },function(error){
                console.log(error);
            });
        }
    };
    $scope.delPiece = function(parentKey){
        console.log(PiecesArr,parentKey,PiecesArr[parentKey]);
        RequestService.Request(commonConfig.cloudApi+'cloud/usercloudindexmodule/deleteUserData?userId='+$rootScope.User.detail.id+'&moduleId='+PiecesArr[parentKey].id,'DELETE').then(function(res){
            console.log(res);
            if(res.code===0){
                PiecesArr.splice(parentKey,1);
                console.log(PiecesArr);
                uploadPiecesArr(PiecesArr); //上传用户设置的信息
            }
        },function(error){
            console.log(error);
        });

    }
};
